package com.egao.generator.controller;

import com.egao.generator.expand.UpdateConfig;
import com.egao.generator.expand.UpdateUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by longhao on 2021/11/2
 */
@RequestMapping("/api/manager")
@RestController()
public class ManagerController {
    @Value("${gen.cache}")
    private Integer cache;


    /**
     * 执行更新
     */
    @PostMapping()
    public Map<String, Object> executeUpdate(@RequestBody UpdateConfig updateConfig) {
        String ses_path="/data1/ses/ses-frontend";
        String ses_out_path="/data1/ses/ses-public-frontend";
        if (updateConfig.getSystemType().equals("ses")){
            updateConfig.setTargetPath(ses_path);
        }else{
            updateConfig.setTargetPath(ses_out_path);
        }
        //清空临时目录
        String tmp="/tmp/ses_zip_target";
        execute("rm -rf "+tmp);
        execute("mkdir "+tmp);
        //解压到tmp目录
        String filePath=new UpdateUtil(cache).getFrontendDir()+"/"+updateConfig.getFilePath();
        Map<String, Object> result1=execute("tar zvxf "+filePath+" -C "+tmp);
        if (result1.get("code").equals(1)){
            return result1;
        }
        //清空target目录
        String cmd0="rm -rf "+ updateConfig.getTargetPath()+"/*";
//        execute(cmd0);
        //移动tmp目录到target目录
        String cmd1="cp -f "+tmp+"/* "+updateConfig.getTargetPath();
        return execute(cmd1);
    }

    private Map<String, Object> execute(String commond){
        try {
            if (commond == null || commond.length()==0) return error("命令不能为空");
            Runtime runtime = Runtime.getRuntime();
            Process pro = runtime.exec(commond);
            int status = pro.waitFor();
            if (status != 0)
            {
                return error("Failed to call shell's command");
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            StringBuffer strbr = new StringBuffer();
            String line;
            while ((line = br.readLine())!= null)
            {
                strbr.append(line).append("\n");
            }

            String result = strbr.toString();
            return ok("执行成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
    }

    /**
     * 执行shell命令
     */
    @PostMapping("/exec")
    public Map<String, Object> executeShell(@RequestBody String commond) {
        return execute(commond);
    }

    /**
     * 上传模板
     */
    @PostMapping("/upload")
    public Map<String, Object> uploadFile(MultipartFile file) {
        if (new UpdateUtil(cache).upload(file)) {
            return ok("上传成功", file.getOriginalFilename());
        }
        return error("上传失败");
    }

    /**
     * 获取文件列表
     */
    @GetMapping("/list")
    public Map<String, Object> list() {
        return ok("查询成功",new UpdateUtil(cache).listTpl());
    }

    /**
     * 获取文件列表
     */
    @GetMapping("/delete")
    public Map<String, Object> delete(String file) {
        return ok("删除成功",new UpdateUtil(cache).delete(file));
    }

    /**
     * 下载压缩包
     */
    @GetMapping("/download")
    public void download(String file, HttpServletResponse response) {
        File outFile = new UpdateUtil(cache).getFile(file);
        if (!outFile.exists()) return;
        // 设置下载文件header
        response.setContentType("application/force-download");
        String fileName = outFile.getName();
        try {
            fileName = URLEncoder.encode(fileName, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        // 输出文件流
        OutputStream os = null;
        BufferedInputStream is = null;
        try {
            os = response.getOutputStream();
            is = new BufferedInputStream(new FileInputStream(outFile));
            byte[] bytes = new byte[1024 * 256];
            int len;
            while ((len = is.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 返回结果信息
     */
    private Map<String, Object> ok(String msg, Object data) {
        return result(0, msg, data);
    }

    private Map<String, Object> error(String msg) {
        return result(1, msg, null);
    }

    private Map<String, Object> result(Integer code, String msg, Object data) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("msg", msg);
        map.put("data", data);
        return map;
    }
}
